'use strict';

import { AlertIOS } from 'react-native'

//第三方组件
import sha1 from 'sha1'

//自定义组件
import request from '../common/request'
import config from '../common/config'

let upload = {};

upload.CLOUDINARY = {
  cloud_name: 'annres',
  api_key: '111554122465279',
  api_secret: '-gfGld3Qoc1SZWgCm0xADmQHqPA',
  base: 'http://res.cloudinary.com/annres',
  image: 'https://api.cloudinary.com/v1_1/annres/image/upload',
  video: 'https://api.cloudinary.com/v1_1/annres/video/upload',
  audio: 'https://api.cloudinary.com/v1_1/annres/raw/upload'
};

/**
 * 获取签名
 */
upload.getSignature = function(accessToken, folder, tags, timestamp, type){
  //请求签名接口，获取签名值
  return request.post(config.api.base + config.api.signature, {
    accessToken: accessToken,
    folder: folder, tags: tags,
    timestamp: timestamp, type: type
  }).then((data) => {
    if (data && data.success) {
      /*以下代码实际为服务端时间，服务端返回的data.data即为签名结果，但因现在是使用rap模拟数据，所以在客户端完成*/

      //签名-所有的请求参数包括timestamp参数但不包括“api_key '和'文件'参数签名
      let signature = 'folder=' + folder + '&tags=' + tags + '&timestamp=' + timestamp + upload.CLOUDINARY.api_secret;
      //进行sha1加密
      signature = sha1(signature);

      return signature;
    }
  });
};

/*
 * 上传图片到cloudinary图床
 * file=要上传的文件，tag=图片标记，folder=存放的文件夹
 */
upload.image = function (file, timestamp, tags, folder, signature, callback) {
  //拿到签名后，合成cloudinary图床上传需要的表单数据
  let body = new FormData();
  body.append('folder', folder);
  body.append('timestamp', timestamp);
  body.append('signature', signature);
  body.append('tags', tags);
  body.append('api_key', this.CLOUDINARY.api_key);
  body.append('resource_type', 'image');
  body.append('file', file);

  //执行上传操作
  this._upload(body, this.CLOUDINARY.image, callback);
}


//上传
upload._upload = function (body, url, callback) {
  let xhr = new XMLHttpRequest();

  xhr.open('POST', url);

  //请求完成
  xhr.onload = () => {
    console.log('xhr.onload')

    if (xhr.status != 200) {
      return AlertIOS.alert('上传失败，状态值' + xhr.status + '，请重试');
      console.log(xhr);
    }
    if (!xhr.responseText) {
      return AlertIOS.alert('服务器异常，请重试');
      console.log(xhr);
    }

    let response;
    try {
      response = JSON.parse(xhr.responseText);
    } catch (err) {
      console.log('xhr.responseText转json出错');
      console.log(err)
    }

    if(response) {
      callback(response);  //调用回调函数
    }
    else {
      console.log(xhr); //未知错误
    }
  };
  //发送请求
  xhr.send(body);
};

module.exports = upload;
